package com.ruoyi.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.admin.domain.entity.InventoryModel;
import com.ruoyi.admin.domain.entity.ProfitModel;
import com.ruoyi.admin.domain.entity.ReturnGoodsModel;
import com.ruoyi.admin.domain.entity.SchedulingModel;
import com.ruoyi.admin.domain.vo.request.atricle.AtriclePageJoinRequest;
import com.ruoyi.admin.domain.vo.request.returnGood.ReturnGoodsAddRequest;
import com.ruoyi.admin.domain.vo.request.returnGood.ReturnGoodsJoinRequest;
import com.ruoyi.admin.domain.vo.response.atricle.AtriclePageJoinResponse;
import com.ruoyi.admin.domain.vo.response.atricle.AtriclePageResponse;
import com.ruoyi.admin.domain.vo.response.returnGood.ReturnGoodsJoinResponse;
import com.ruoyi.admin.mapper.InventoryMapper;
import com.ruoyi.admin.mapper.ProfitMapper;
import com.ruoyi.admin.mapper.ReturnGoodsMapper;
import com.ruoyi.admin.mapper.SchedulingMapper;
import com.ruoyi.admin.domain.vo.response.returnGood.ReturnGoodsPageResponse;
import com.ruoyi.admin.domain.vo.response.returnGood.ReturnGoodsResponse;
import com.ruoyi.admin.service.ReturnGoodsService;
import com.ruoyi.common.api.Result;
import com.ruoyi.common.api.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 退货表(ReturnGoods)Service实现类
 *
 * @author jianhan
 * @date 2023-01-31 09:53:25
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ReturnGoodsServiceImpl extends ServiceImpl<ReturnGoodsMapper, ReturnGoodsModel> implements ReturnGoodsService {

    private static final Logger logger = LoggerFactory.getLogger(ReturnGoodsServiceImpl.class);

    @Resource
    private InventoryMapper inventoryMapper;

    @Resource
    private SchedulingMapper schedulingMapper;

    @Resource
    private ProfitMapper profitMapper;

    @Override
    public Result<ReturnGoodsResponse> getId(Long returnGoodsId) {
        ReturnGoodsModel returnGoodsModel = this.getById(returnGoodsId);
        if (returnGoodsModel != null) {
            ReturnGoodsResponse returnGoodsResponse = new ReturnGoodsResponse(returnGoodsModel);
            return Result.success(returnGoodsResponse);
        }
        return Result.failed(ResultCode.DATA_NOT_EXIST);
    }

    @Override
    public Result<ReturnGoodsPageResponse> page(Page<ReturnGoodsJoinRequest> page, ReturnGoodsJoinRequest returnGoodsJoinRequest) {
        Page<ReturnGoodsJoinResponse> pages = baseMapper.queryPage(page,returnGoodsJoinRequest);
        ReturnGoodsPageResponse returnGoodsPageResponse = new ReturnGoodsPageResponse(pages);
        return Result.success(returnGoodsPageResponse);
    }

    @Override
    @Transactional
    public Result add(ReturnGoodsAddRequest returnGoodsModel) {
        List<SchedulingModel> schedulingModels = new ArrayList<>();
        if (returnGoodsModel.getSchedulingId()!= null) {
            schedulingModels = schedulingMapper.selectList(new QueryWrapper<SchedulingModel>().eq("id", returnGoodsModel.getSchedulingId()));
        }else {
            schedulingModels = schedulingMapper.selectList(new QueryWrapper<SchedulingModel>().eq("order_number", returnGoodsModel.getOrderNumber()));
        }
        if (schedulingModels != null & schedulingModels.size() > 0) {
            SchedulingModel schedulingModel = schedulingModels.get(0);
            List<ReturnGoodsModel> schedulings = baseMapper.selectList(new QueryWrapper<ReturnGoodsModel>().eq("scheduling_id", schedulingModel.getId()));
            if (schedulings!= null & schedulings.size() > 0) {
                return Result.failed("该订单已存在退货信息，不可重复退货");
            }
            returnGoodsModel.setSchedulingId(schedulingModel.getId());
            if (returnGoodsModel.getReturnNum()>schedulingModel.getNumber()) {
                return Result.failed("数量超过该订单的数量，订单数量为："+schedulingModel.getNumber());
            }
            List<InventoryModel> inventoryModels = inventoryMapper.selectList(new QueryWrapper<InventoryModel>().eq("atricle_id", schedulingModel.getArticleId()));
            List<ProfitModel> profitModels = profitMapper.selectList(new QueryWrapper<ProfitModel>().eq("article_id", schedulingModel.getArticleId()));
            if (schedulingModel.getType().equals("2")) {
                //销售
                //修改库存
                if (inventoryModels != null && inventoryModels.size() > 0) {
                    InventoryModel inventoryModel = inventoryModels.get(0);
                    inventoryModel.setNumber(inventoryModel.getNumber() + returnGoodsModel.getReturnNum());
                    inventoryModel.setTotalPrice(inventoryModel.getTotalPrice().add(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    inventoryModel.setPrice(inventoryModel.getTotalPrice().divide(BigDecimal.valueOf(inventoryModel.getNumber()),BigDecimal.ROUND_CEILING));
                    inventoryMapper.updateById(inventoryModel);
                } else {
                    throw new RuntimeException("库存表查询不到该商品信息，请联系管理员");
                }
                //修改报表
                if (profitModels != null && profitModels.size() > 0) {
                    ProfitModel profitModel = profitModels.get(0);
                    profitModel.setOutputAmount(profitModel.getOutputAmount().subtract(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    profitModel.setGrossMargin(profitModel.getGrossMargin().subtract(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    profitMapper.updateById(profitModel);
                } else {
                    throw new RuntimeException("报表查询不到该商品信息，请联系管理员");
                }
            } else if (schedulingModel.getType().equals("1")) {
                //采购
                //修改库存
                if (inventoryModels != null && inventoryModels.size() > 0) {
                    InventoryModel inventoryModel = inventoryModels.get(0);
                    inventoryModel.setNumber(inventoryModel.getNumber() - returnGoodsModel.getReturnNum());
                    inventoryModel.setTotalPrice(inventoryModel.getTotalPrice().subtract(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    inventoryModel.setPrice(inventoryModel.getTotalPrice().divide(BigDecimal.valueOf(inventoryModel.getNumber())));
                    inventoryMapper.updateById(inventoryModel);
                } else {
                    throw new RuntimeException("库存表查询不到该商品信息，请联系管理员");
                }
                //修改报表
                if (profitModels != null && profitModels.size() > 0) {
                    ProfitModel profitModel = profitModels.get(0);
                    profitModel.setOutputAmount(profitModel.getInputAmount().subtract(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    profitModel.setGrossMargin(profitModel.getGrossMargin().add(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    profitMapper.updateById(profitModel);
                } else {
                    throw new RuntimeException("报表查询不到该商品信息，请联系管理员");
                }
            }
        }else{
            return Result.failed("找不到该订单");
        }
        Boolean result = this.save(returnGoodsModel.getReturnGoodsModel());
        if (result) {
            return Result.success();
        }
        return Result.failed("添加失败");
    }

    @Override
    public Result update(ReturnGoodsModel returnGoodsModel) {
        Boolean result = this.updateById(returnGoodsModel);
        if (result) {
            return Result.success();
        }
        return Result.failed("更新失败");
    }


    @Override
    public Boolean delete(Long returnGoodsId) {
        ReturnGoodsModel returnGoodsModel = baseMapper.selectById(returnGoodsId);
        List<SchedulingModel> schedulingModels = schedulingMapper.selectList(new QueryWrapper<SchedulingModel>().eq("id", returnGoodsModel.getSchedulingId()));
        if (schedulingModels != null & schedulingModels.size() > 0) {
            SchedulingModel schedulingModel = schedulingModels.get(0);
            List<InventoryModel> inventoryModels = inventoryMapper.selectList(new QueryWrapper<InventoryModel>().eq("atricle_id", schedulingModel.getArticleId()));
            List<ProfitModel> profitModels = profitMapper.selectList(new QueryWrapper<ProfitModel>().eq("atricle_id", schedulingModel.getArticleId()));
            if (schedulingModel.getType().equals("2")) {
                //销售
                //修改库存
                if (inventoryModels != null && inventoryModels.size() > 0) {
                    InventoryModel inventoryModel = inventoryModels.get(0);
                    inventoryModel.setNumber(inventoryModel.getNumber() - returnGoodsModel.getReturnNum());
                    inventoryModel.setTotalPrice(inventoryModel.getTotalPrice().subtract(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    inventoryModel.setPrice(inventoryModel.getTotalPrice().divide(BigDecimal.valueOf(inventoryModel.getNumber())));
                } else {
                    throw new RuntimeException("库存表查询不到该商品信息，请联系管理员");
                }
                //修改报表
                if (profitModels != null && profitModels.size() > 0) {
                    ProfitModel profitModel = profitModels.get(0);
                    profitModel.setOutputAmount(profitModel.getOutputAmount().add(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    profitModel.setGrossMargin(profitModel.getGrossMargin().add(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    profitMapper.updateById(profitModel);
                } else {
                    throw new RuntimeException("报表查询不到该商品信息，请联系管理员");
                }
            } else if (schedulingModel.getType().equals("1")) {
                //采购
                //修改库存
                if (inventoryModels != null && inventoryModels.size() > 0) {
                    InventoryModel inventoryModel = inventoryModels.get(0);
                    inventoryModel.setNumber(inventoryModel.getNumber() + returnGoodsModel.getReturnNum());
                    inventoryModel.setTotalPrice(inventoryModel.getTotalPrice().add(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    inventoryModel.setPrice(inventoryModel.getTotalPrice().divide(BigDecimal.valueOf(inventoryModel.getNumber())));
                    inventoryMapper.updateById(inventoryModel);
                } else {
                    throw new RuntimeException("库存表查询不到该商品信息，请联系管理员");
                }
                //修改报表
                if (profitModels != null && profitModels.size() > 0) {
                    ProfitModel profitModel = profitModels.get(0);
                    profitModel.setOutputAmount(profitModel.getInputAmount().add(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    profitModel.setGrossMargin(profitModel.getGrossMargin().subtract(schedulingModel.getPrice().multiply(BigDecimal.valueOf(returnGoodsModel.getReturnNum()))));
                    profitMapper.updateById(profitModel);
                } else {
                    throw new RuntimeException("报表查询不到该商品信息，请联系管理员");
                }
            }
        }
        Boolean result = this.removeById(returnGoodsId);
        return result;
    }

    private QueryWrapper<ReturnGoodsModel> queryWrapper(ReturnGoodsModel returnGoodsModel) {
        QueryWrapper<ReturnGoodsModel> queryWrapper = new QueryWrapper<>();
        
        /*
           写搜索条件
        */
        queryWrapper.orderByDesc("id");
        return queryWrapper;
    }

}
